<?php
namespace Modules\User\Traits;

use ThrowException;

// 可使用人群价
trait GroupPriceable 
{
    // 人群价
    public function group_prices()
    {
        $resourceType = str_singular($this->table);
        return $this->hasMany('\Modules\User\Entities\UserGroupPrice', 'target_id')->where('target_type', $resourceType)->orderBy('list_weight', 'desc')->orderBy('id', 'desc');
    }

    // 设置人群价
    public function setGroupPrices($list)
    {
    	$items = $this->group_prices; 

        $resourceType = str_singular($this->table);
    	foreach ($list as $key => $item) {
    		$existItem = $items->where('group_id', $item['group_id'])->first();
    		$list[$key]['uuid'] = uniqid();
    		$list[$key]['target_type'] = $resourceType;

    		if ($existItem) {
	    		$list[$key]['sales'] = $existItem->sales;
    		}
    	}

    	// 删除旧的
    	foreach ($items as $item) {
    		$item->forceDelete();
    	}

    	$this->group_prices()->createMany($list);

    	return [];
    }
}